Given(/^I am a super admin$/) do
  admin
end

def admin
  @admin ||= create(:admin)
end

When(/^I sign in$/) do
  visit '/admins/sign_in'
  fill_in :admin_email, with: 'super@edm.com'
  fill_in :admin_password, with: 'Sup3rAdm!n'
  click_button 'Sign in'
end

Then(/^I should see "([^"]*)" link$/) do |arg|
  page.should have_link(arg)
end

When(/^I click "([^"]*)" link$/) do |arg|
  click_link arg
end

Then(/^I should be able to choose multiple permissions$/) do
  puts page.body
  %w(create_mail deliver_mail deliver_test_mail
     view_report create_admin create_user
     create_tester create_user_group).each do |permission|
    page.should have_field(permission.humanize)
  end
end

When(/^I fill the name with "([^"]*)"$/) do |arg|
  fill_in :role_name, with: arg
end

And(/^I check "([^"]*)", "([^"]*)", "([^"]*)"$/) do |arg1, arg2, arg3|
  @permissions = [arg1, arg2, arg3]
  @permissions.each do |arg|
    check arg
  end
end

And(/^I submit the form$/) do
  click_button('Create Role')
end

Then(/^a new role should be created\.$/) do
  permissions = Role.last!.permissions.map{|permission| permission.action.humanize}
  (@permissions - permissions).should be_empty
  (permissions - @permissions).should be_empty
end

Given(/^I have permission to "([^"]*)"$/) do |action|
  permission = Permission.find_by!(action: action.gsub(/\s+/, '_'))
  role = Role.new(name: 'tmp')
  role.grants.build(permission: permission)
  admin.update(role: role)
end

Given(/^I don't have permission to "([^"]*)"$/) do |arg|
  admin.update(role: Role.new)
end

Then(/^I should not see "([^"]*)" link$/) do |arg|
  page.should_not have_link(arg)
end

And(/^I should be denied to visit "([^"]*)"$/) do |path|
  lambda{
    visit path
  }.should raise_error(ActionController::RoutingError)
end